package com.ace.user.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * druid配置
 * @Author yudong
 * @Date 2018年07月02日 下午4:28
 */
@Configuration

public class DruidConfig {

    @Autowired
    private DruidParameterConfig druidParameter;


    /**
     * 配置 DataSource
     *
     * @return
     */
    @Bean
    public DataSource druidDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(druidParameter.getUrl());
        datasource.setUsername(druidParameter.getUserName());
        datasource.setPassword(druidParameter.getPassword());
        datasource.setDriverClassName(druidParameter.getDriveClassName());
        datasource.setInitialSize(druidParameter.getInitialSize());
        datasource.setMinIdle(druidParameter.getMinIdle());
        datasource.setMaxActive(druidParameter.getMaxActive());
        datasource.setMaxWait(druidParameter.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(druidParameter.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(druidParameter.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(druidParameter.getValidationQuery());
        datasource.setTestWhileIdle(druidParameter.getTestWhileIdle());
        datasource.setTestOnBorrow(druidParameter.getTestOnBorrow());
        datasource.setTestOnReturn(druidParameter.getTestOnReturn());
        try {
            datasource.setFilters(druidParameter.getFilters());
        }catch (SQLException e){
            e.printStackTrace();
        }
        return datasource;
    }


    @Data
    @Component
    @ConfigurationProperties(prefix = "spring.datasource")
    public class DruidParameterConfig {
        private String driveClassName;
        private String url;
        private String userName;
        private String password;
        private String xmlLocation;
        private String typeAliasesPackage;
        private String filters;
        private int maxActive;
        private int initialSize;
        private long maxWait;
        private int minIdle;
        private long timeBetweenEvictionRunsMillis;
        private long minEvictableIdleTimeMillis;
        private String validationQuery;
        private Boolean testWhileIdle;
        private Boolean testOnBorrow;
        private Boolean testOnReturn;
        private String poolPreparedStatements;
        private String maxOpenPreparedStatements;

    }
}
